package org.apache.pdfbox.arktaohtml.Utils;

import org.apache.pdfbox.arktaohtml.Config;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;

public class Utils {
    /**
     * 产生随机字符串
     *
     * @param length 字符串的长度
     * @return 所产生的字符串
     */
    public static String getRandomStr(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取文件的名称
     * 如 "C:\Users\WS\IdeaProjects\PPT2Image\src\cn\arktao\lessonplanhtml\Utils\Utils.java"
     * 返回 Utils.java
     *
     * @param file
     * @return
     */
    public static String basename(String file) {

        return file.substring(file.lastIndexOf("/") + 1);
    }




    public static boolean delDir(File file) {
        if (file == null) return true;
        if (!file.exists()) {
            return false;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                Utils.delDir(f);
            }
        }
        return file.delete();
    }

    /**
     * 同步图片文件
     *
     * @return
     */
    public static boolean rsyncImageFile() throws Exception {

        String cmd = " -r --stats --port=" + Config.RSYNC_PORT + " " + Config.IMAGE_TRANSTEMPSAVE_PATH + " sunwu@" + Config.RSYNC_HOST + "::" + Config.RSYNC_MODULE + " --password-file=" + Config.RSYNC_PASSWORD;
        String tcmd = Config.RSYNC_EXE + cmd.replace("org.fit.pdfdom.D:", "/cygdrive/d").replace("\\", "/");
        StringBuilder sb = new StringBuilder();
        Process child = Runtime.getRuntime().exec(tcmd);
        InputStream in = child.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        in.close();
        child.waitFor();
        return sb.toString().contains("Total bytes sent");

    }

    /**
     * 获取文件的 mime 类型
     *
     * @param filename
     * @return
     */
    public static String getContentType(String filename) {
        String type = null;
        Path path = Paths.get(filename);
        try {
            type = Files.probeContentType(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return type;
    }

}
